package com.xinou.daily_report.expand.sso.mini;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.xinou.common.base.config.ApiResponse;
import com.xinou.common.base.exception.BusException;
import com.xinou.common.enumerate.HttpStatusEnum;
import com.xinou.common.enumerate.TokenTypeEnum;
import com.xinou.common.util.JwtUtil;
import com.xinou.sso.enumerate.HttpSsoStatusEnum;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 信鸥 Mini jwt 过滤器 <br>
 *
 * @author lizhongyuan
 * @date 2021/5/28
 */
public class MiniFilter extends BasicHttpAuthenticationFilter {

    /**
     * 前置处理
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 过滤器拦截请求的入口方法
     * 返回 true 则允许访问
     * 返回false 则禁止访问，会进入 onAccessDenied()
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //判断请求的请求头是否带上 "token"
        if (isLoginAttempt(request, response)) {
            //如果存在，则进入 executeLogin 方法执行登入，检查 token 是否正确
            try {
                return executeLogin(request, response);
            } catch (Exception e) {
                //token 错误
                responseError(response, e);
            }
        }
        //如果请求头不存在 token，则可能是执行登陆操作或者是游客状态访问，无需检查 token，直接返回 true
        return true;
    }

    /**
     * 身份验证,检查 JWT token 是否合法
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        try {
            AuthenticationToken token = createToken(request, response);
            getSubject(request, response).login(token);
            return true;
        } catch (Exception e) {
            responseError(response, e);
        }
        return false;
    }

    /**
     * 从 Header 里提取 JWT token
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String webToken = WebUtils.toHttp(request).getHeader(TokenTypeEnum.TYPE_WEB.getTokenName());
        Map<String, Claim> claimMap = JwtUtil.getJwtClaimsNoVerify(webToken);
        Integer type = JwtUtil.getJwtClaimValueNoVerify(claimMap, "tokenType", Integer.class);
        if (type == null || TokenTypeEnum.tokenTypeEnum(type) != TokenTypeEnum.TYPE_WEB) {
            throw new BusException(HttpStatusEnum.RE_CODE_NO_HAVE_TOKEN);
        }
        return new MiniToken(webToken, JwtUtil.getJwtClaimValueNoVerify(claimMap, "userId", Long.class));
    }

    /**
     * 判断用户是否想要登入。
     * 检测 header 里面是否包含 token 字段
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        return WebUtils.toHttp(request).getHeader(TokenTypeEnum.TYPE_WEB.getTokenName()) != null;
    }

    /**
     * 非法url返回身份错误信息
     */
    private void responseError(ServletResponse response, Exception exception) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("utf-8");
            out = response.getWriter();
            response.setContentType("application/json; charset=utf-8");
            ApiResponse apiResponse;
            if (exception.getCause() instanceof BusException) {
                BusException busException = ((BusException) exception.getCause());
                apiResponse = new ApiResponse(busException.getCode(), busException.getMessage());
            } else if (exception instanceof AuthenticationException) {
                apiResponse = new ApiResponse(HttpSsoStatusEnum.RE_CODE_AUTH_ERROR);
            } else if (exception instanceof ShiroException) {
                apiResponse = new ApiResponse(HttpSsoStatusEnum.RE_CODE_UN_LOGIN);
            } else {
                apiResponse = new ApiResponse(HttpSsoStatusEnum.RE_CODE_UN_LOGIN);
            }
            out.print(JSONObject.toJSONString(apiResponse));
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
